/*global pi */

pi.mod.define('pi.os.window', function (pi) {
	"use strict";
	var module = {};
	
	var user32 = [
		["SendMessageW", pi.vcall.TYPE_INT, [pi.vcall.TYPE_INT, pi.vcall.TYPE_INT, pi.vcall.TYPE_INT, pi.vcall.TYPE_INT]],
		["GetParent", pi.vcall.TYPE_INT, [pi.vcall.TYPE_INT]],
		["ScreenToClient", pi.vcall.TYPE_BOOL, [pi.vcall.TYPE_INT, pi.vcall.TYPE_POINTER]],
	];

	// 注册所有 vcall 函数句柄
	pi.vcall.makeVCall("user32.dll", module, user32);

	/*
	 * The SendMessage function sends the specified message to a window or windows. It calls the window procedure for the specified window and does not return until the window procedure has processed the message. 
	 * see msdn for detail.
	 */	
	module.sendMessage = function(wnd, msg, wParam, lParam){
		return user32.SendMessageW(wnd, msg, wParam, lParam);
	};
	
	/*
	 * The GetParent function retrieves a handle to the specified window's parent or owner
	 * wnd: Handle to the window whose parent window handle is to be retrieved. 
	 */
	module.getParent = function (wnd) {
		return user32.GetParent(wnd);
	};

	/*
	 * get window text, imp by sendMessage
	 * wnd: Handle to the window whose text is to be retrieved. 
	 * maxChars: Specifies the maximum number of TCHARs to be copied, including the terminating null character. 
	 */	
	module.getWindowText = function(wnd, maxChars){
		maxChars = pi.util.defaultValue(maxChars, 1024);
		//var buf = pi.lang.createArray(maxChars);
		var buf = new ArrayBuffer(maxChars);
		var addr = pi.vcall.getBufferAddress(buf);
		if(addr){
			module.sendMessage(wnd, pi.os.winh.WM_GETTEXT, maxChars, addr);
			return pi.vcall.readBuffer(buf, pi.vcall.TYPE_STRING);
		}
		else
			return "error";
	};
	
	/*
	 * screenToClient
	 * wnd: Handle to the window
	 * screenPos: screenPos.x & screenPos.y 包含坐标信息
	 */
	module.screenToClient = function(wnd, screenPos){
		var buf = new ArrayBuffer(8);
		pi.vcall.writeBuffer(screenPos.x, buf, pi.vcall.TYPE_INT, 0);
		pi.vcall.writeBuffer(screenPos.y, buf, pi.vcall.TYPE_INT, 4);
		if(user32.ScreenToClient(wnd, buf)){
			screenPos.x = pi.vcall.readBuffer(buf, pi.vcall.TYPE_INT, 0);
			screenPos.y = pi.vcall.readBuffer(buf, pi.vcall.TYPE_INT, 4);
			return true;
		}
		else{
			return false;
		}
	};
	
	return module;
});